import React, { Component } from 'react'
import { Redirect, Route, Switch } from 'react-router-dom'
import { Layout } from 'antd'
import memoryUtils from '../../utils/memoryUtils'
import menuList from '../../config/menuConfig'

import LeftNav from '../../components/left-nav/left-nav'
import Header from '../../components/header/header'
import Home from '../home/home'
import Category from '../category/category'
import Product from '../product/product'
import Role from '../role/role'
import User from '../user/user'
import Bar from '../charts/bar'
import Line from '../charts/line'
import Pie from '../charts/pie'

const { Footer, Sider, Content } = Layout

export default class Admin extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  //判断是否有权限
  getAuthRoute = () => {
    const menus = memoryUtils.user.role.menus
    const username = memoryUtils.user.username
    console.log(menus, username)
    return menuList.map((item, index) => {
      const { key, isPublic, component } = item
      /*
       1. 如果当前用户是admin
       2. 如果当前item是公开的
       3. 当前用户有此item的权限: key有没有menus中
        */
      if (username === 'admin') {
        //如果是管理员全部接入
        if (item.children) {
          return item.children.map(i => {
            return <Route exact path={i.key} component={i.component} />
          })
        } else {
          return <Route exact key={index} path={key} component={component} />
        }
      } else {
        //非管理员如果有isPublic属性的也接入其他根据权限校验动态渲染路由
        if (isPublic || (menus.indexOf(key) !== -1 && !item.children)) {
          return <Route exact key={index} path={key} component={component} />
        } else if (!!item.children) {
          // 4. 如果当前用户有此item的某个子item的权限
          return item.children.map(i => {
            console.log(i)
            if (!!menus.indexOf(i.key) !== -1) {
              return <Route exact path={i.key} component={i.component} />
            }
          })
        }
      }
    })
  }
  render() {
    const user = memoryUtils.user
    // 如果内存没有存储user ==> 当前没有登陆
    if (!user || !user._id) {
      // 自动跳转到登陆(在render()中)
      return <Redirect to="/login" />
    }

    return (
      <Layout style={{ minHeight: '100%' }}>
        <Sider>
          <LeftNav></LeftNav>
        </Sider>
        <Layout>
          <Header />
          <Content style={{ margin: 20, backgroundColor: '#fff' }}>
            <Switch>
              <Redirect from="/" exact to="/home" />
              {this.getAuthRoute()}
              <Redirect to="/home" />
            </Switch>
          </Content>
          <Footer style={{ textAlign: 'center', color: '#cccccc' }}>推荐使用谷歌浏览器，可以获得更佳页面操作体验</Footer>
        </Layout>
      </Layout>
    )
  }
}
